using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TradeFlow.Server.Dto;
using TradeFlow.Server.Models;
using SqlSugar;
using TradeFlow.Server.Language;

namespace TradeFlow.Server.Service
{
    /// <summary>
    /// 对账单表头服务类
    /// </summary>
    public class JxAccountHeadService : IApplicationService
    {
        private readonly SugarRepository<JxAccountHead> _repository;
        private readonly SugarRepository<JxAccountList> _listRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="listRepository"></param>
        /// <param name="localizer"></param>
        public JxAccountHeadService(SugarRepository<JxAccountHead> repository, SugarRepository<JxAccountList> listRepository)
        {
            _repository = repository;
            _listRepository = listRepository;
       
        }
        //public Task<PagingResult<AccountInfo>> QueryAccountsAsync(PagingCriteria criteria)
        //{
        //    return Database.Query<JxAccountHead>(criteria).ToPageAsync<AccountInfo>();
        //}

        //public async Task<AccountInfo> GetDefaultAccountAsync(string type)
        //{
        //    return new AccountInfo
        //    {
        //        Type = type,
        //        AccountNo = await Database.GetMaxAccountNoAsync(type),
        //        Status = FlowStatus.Save,
        //        AccountDate = DateTime.Now
        //    };
        //}

        //public async Task<Result> DeleteAccountsAsync(List<AccountInfo> infos)
        //{
        //    if (infos == null || infos.Count == 0)
        //        return Result.Error(Language.SelectOneAtLeast);

        //    var database = Database;
        //    var oldFiles = new List<string>();
        //    var result = await database.TransactionAsync(Language.Delete, async db =>
        //    {
        //        foreach (var item in infos)
        //        {
        //            await db.DeleteFilesAsync(item.Id, oldFiles);
        //            await db.DeleteAsync<JxAccountList>(d => d.HeadId == item.Id);
        //            await db.DeleteAsync<JxAccountHead>(item.Id);
        //        }
        //    });
        //    if (result.IsValid)
        //        AttachFile.DeleteFiles(oldFiles);
        //    return result;
        //}

        //public async Task<Result> SaveAccountAsync(UploadInfo<AccountInfo> info)
        //{
        //    var database = Database;
        //    var model = await database.QueryByIdAsync<JxAccountHead>(info.Model.Id);
        //    model ??= new JxAccountHead();
        //    model.FillModel(info.Model);

        //    var vr = model.Validate(Context);
        //    if (!vr.IsValid)
        //        return vr;

        //    var fileFiles = info.Files?.GetAttachFiles(nameof(JxAccountHead.Files), "AccountFiles");
        //    return await database.TransactionAsync(Language.Save, async db =>
        //    {
        //        if (model.IsNew)
        //            model.AccountNo = await db.GetMaxAccountNoAsync(model.Type);
        //        await db.AddFilesAsync(fileFiles, model.Id, key => model.Files = key);
        //        await db.SaveAsync(model);
        //        info.Model.Id = model.Id;
        //    }, info.Model);
        //}
        /// <summary>
        /// 查询对账单表头分页列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<RestfulResult<PageResult<JxAccountHead>>> GetPagesAsync(JxAccountHeadPageParam param)
        {
            try
            {
                var query = _repository.AsQueryable();
                
                // 根据参数进行条件筛选
                if (!string.IsNullOrEmpty(param.Type))
                {
                    query = query.Where(x => x.Type == param.Type);
                }
                if (!string.IsNullOrEmpty(param.AccountNo))
                {
                    query = query.Where(x => x.AccountNo.Contains(param.AccountNo));
                }
                if (!string.IsNullOrEmpty(param.Status))
                {
                    query = query.Where(x => x.Status == param.Status);
                }
                if (!string.IsNullOrEmpty(param.Partner))
                {
                    query = query.Where(x => x.Partner == param.Partner);
                }
                if (param.StartDate.HasValue)
                {
                    query = query.Where(x => x.AccountDate >= param.StartDate);
                }
                if (param.EndDate.HasValue)
                {
                    // 结束日期加一天，包含当天的所有数据
                    query = query.Where(x => x.AccountDate < param.EndDate.Value.AddDays(1));
                }

                // 执行分页查询
                var result = await query.OrderBy(x => x.AccountDate, OrderByType.Desc).ToPageAsync(param.CurrentPage, param.PageSize);
                
                return new RestfulResult<PageResult<JxAccountHead>>()
                {
                    Data = result,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<PageResult<JxAccountHead>>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取所有对账单表头列表
        /// </summary>
        /// <returns></returns>
        public async Task<RestfulResult<List<JxAccountHead>>> GetListAsync()
        {
            try
            {
                var list = await _repository.AsQueryable().ToListAsync();
                return new RestfulResult<List<JxAccountHead>>()
                {
                    Data = list,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<List<JxAccountHead>>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 根据ID获取对账单表头
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RestfulResult<JxAccountHead>> GetByIdAsync(long id)
        {
            try
            {
                var entity = await _repository.AsQueryable().Where(x => x.Id == id).FirstAsync();
                return new RestfulResult<JxAccountHead>()
                {
                    Data = entity,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<JxAccountHead>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 增加对账单表头
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> AddAsync(JxAccountHead entity)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrEmpty(entity.AccountNo))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账单号不能为空"
                    };
                }
                if (string.IsNullOrEmpty(entity.Type))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "类型不能为空"
                    };
                }
                if (string.IsNullOrEmpty(entity.Partner))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "往来单位不能为空"
                    };
                }

                // 设置创建信息
                entity.CreateTime = DateTime.Now;

                // 保存表头数据
                await _repository.InsertAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "添加成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "添加失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 更新对账单表头
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> UpdateAsync(JxAccountHead entity)
        {
            try
            {
                // 检查是否存在
                var oldEntity = await _repository.AsQueryable().Where(x => x.Id == entity.Id).FirstAsync();
                if (oldEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                // 已确认的对账单不允许修改
                if (oldEntity.Status != "暂存")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "已确认的对账单不能编辑"
                    };
                }

                // 更新数据，不设置UpdateTime
                await _repository.UpdateAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "更新成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "更新失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 删除对账单表头
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> DeleteAsync(List<long> ids)
        {
            try
            {
                // 检查是否有已确认的对账单
                var count = await _repository.AsQueryable().Where(x => ids.Contains(x.Id) && x.Status != "暂存").CountAsync();
                if (count > 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "已确认的对账单不能删除"
                    };
                }

                // 删除关联的表体数据
                var headIdStrings = ids.Select(id => id.ToString()).ToList();
                await _listRepository.DeleteAsync(x => headIdStrings.Contains(x.HeadId));

                // 删除表头数据
                dynamic[] idArray = ids.Select(id => (dynamic)id).ToArray();
                await _repository.DeleteByIdsAsync(idArray);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "删除失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 确认对账单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> ConfirmAsync(long id)
        {
            try
            {
                var entity = await _repository.AsQueryable().Where(x => x.Id == id).FirstAsync();
                if (entity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                if (entity.Status != "暂存")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账单已确认"
                    };
                }

                // 检查是否有表体数据
                var listCount = await _listRepository.AsQueryable().Where(x => x.HeadId == id.ToString()).CountAsync();
                if (listCount == 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账单无表体数据"
                    };
                }

                // 更新状态
                entity.Status = "已对账";
                await _repository.UpdateAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "确认成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "确认失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 开票
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> InvoiceAsync(long id)
        {
            try
            {
                var entity = await _repository.AsQueryable().Where(x => x.Id == id).FirstAsync();
                if (entity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                if (entity.Status != "已对账")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "对账单未确认，无法开票"
                    };
                }

                // 更新状态
                entity.Status = "已开票";
                entity.ModifyTime = DateTime.Now;
                await _repository.UpdateAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "开票成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "开票失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 回款
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> PaymentAsync(long id)
        {
            try
            {
                var entity = await _repository.AsQueryable().Where(x => x.Id == id).FirstAsync();
                if (entity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                if (entity.Status != "已开票")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "账单未开发票，不能回款"
                    };
                }

                // 更新状态
                entity.Status = "已回款";
                entity.ModifyTime = DateTime.Now;
                await _repository.UpdateAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "回款成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "回款失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 生成新的对账单编号
        /// </summary>
        /// <param name="billType"></param>
        /// <returns></returns>
        private string GenerateNewBillNo(string billType)
        {
            // 生成规则：类型前缀 + 年月日 + 4位流水号
            string prefix = "KH";
            if (billType == "供应商对账单")
            {
                prefix = "GYS";
            }

            string dateStr = DateTime.Now.ToString("yyyyMMdd");
            string maxNo = _repository.AsQueryable().Where(x => x.AccountNo.StartsWith(prefix + dateStr)).Max(x => x.AccountNo);
            int sequence = 1;
            if (!string.IsNullOrEmpty(maxNo))
            {
                string seqStr = maxNo.Substring(prefix.Length + dateStr.Length);
                if (int.TryParse(seqStr, out int currentSeq))
                {
                    sequence = currentSeq + 1;
                }
            }

            return $"{prefix}{dateStr}{sequence.ToString("0000")}";
        }
    }
}